<template>
  <div class="echarts-box">
    <div :id="id" :class="className" :style="{ height, width }" />
  </div>
</template>

<script setup lang="ts">
import {  ref, onMounted, watch } from "vue";
import * as echarts from 'echarts';

const props = defineProps({
  id: {
    type: String,
    default: "lineEcharts",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "100%",
    required: true,
  },
  height: {
    type: String,
    default: "220px",
    required: true,
  },
  lineBarData: {
    type: Object,
    default: () => ({
      xAxisData: [],
      sale_amount_list: [],
      sale_cnt_list: [],
      sale_service_amount_list: [],
      sale_service_cnt_list: []
    })
  }
});

const chart: Ref<echarts.ECharts | null> = ref(null);

/** 设置图表  */
const setChartOptions = (data: any) => {
  if (!chart.value) {
    return;
  }
  const options = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    toolbox: {
      feature: {
        dataView: { show: false, readOnly: false },
        magicType: { show: false, type: ['line', 'bar'] },
        restore: { show: false },
        saveAsImage: { show: false }
      }
    },
    legend: {
      data: ['订单金额', '订单量', '退款金额', '退款订单量']
    },
    grid: {
      top: '15%',
      left: '1%',
      right: '1%',
      bottom: '2%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: data.xAxisData,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '金额',
        min: 0,
        axisLabel: {
          formatter: '{value} 元'
        }
      },
      {
        type: 'value',
        name: '单量',
        min: 0,
        axisLabel: {
          formatter: '{value} 单'
        }
      }
    ],
    series: data.series
  };

  chart.value.setOption(options);
};


const getLastMonthDates = function() {
  const today = new Date();
  const oneMonthAgo = new Date(today);
  oneMonthAgo.setMonth(today.getMonth() - 1);

  const dates = [];
  let order_list = [];
  while (oneMonthAgo <= today) {
    const month = String(oneMonthAgo.getMonth() + 1).padStart(2, '0');
    const day = String(oneMonthAgo.getDate()).padStart(2, '0');
    const formattedDate = `${month}月${day}日`;
    dates.push(formattedDate);
    order_list.push(0);
    oneMonthAgo.setDate(oneMonthAgo.getDate() + 1);
  }
  return {dates: dates, order_list: order_list};
}

const loadData = async (data) => {
  const items = getLastMonthDates();
  setChartOptions({
    xAxisData: data?.xAxisData || items.dates,
    series: [
      {
        name: '订单金额',
        type: 'bar',
        tooltip: {
          valueFormatter: function (value) {
            return value as number + ' 元';
          }
        },
        data: data?.sale_amount_list || items.order_list
      },
      {
        name: '订单量',
        type: 'line',
        yAxisIndex: 1,
        tooltip: {
          valueFormatter: function (value) {
            return value as number + ' 单';
          }
        },
        data: data?.sale_cnt_list || items.order_list
      },{
        name: '退款金额',
        type: 'bar',
        tooltip: {
          valueFormatter: function (value) {
            return value as number + ' 元';
          }
        },
        data: data?.sale_service_amount_list || items.order_list
      },
      {
        name: '退款订单量',
        type: 'line',
        yAxisIndex: 1,
        tooltip: {
          valueFormatter: function (value) {
            return value as number + ' 单';
          }
        },
        data: data?.sale_service_cnt_list || items.order_list
      }
    ],
  });
}

// 窗口大小变化时，重置图表大小
const handleResize = () => {
  setTimeout(() => {
    if (chart.value) {
      chart.value.resize();
    }
  }, 100);
};

onMounted(() => {
  chart.value = markRaw(echarts.init(document.getElementById(props.id) as HTMLDivElement));
  loadData();
  window.addEventListener("resize", handleResize);
})

watch(props.lineBarData, (newVal, oldVal) => {
  loadData(newVal);
}, {deep: true});

</script>

<style scoped lang="ts">

</style>
